﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml.Linq;
using BulldogCMS.Core.Storage.Providers;

namespace BulldogCMS.Core.Storage
{
    public class Tree
    {
        private IContentTreeProvider _contentTreeProvider = null;

        public IEnumerable<Node> Nodes
        {
            get
            {
                IEnumerable<Node> nodes = Context.Application.StorageCache.GetSubNodes("/");
                if (nodes != null)
                {
                    return nodes;
                }

                nodes = this._contentTreeProvider.GetRootNodes();
                Context.Application.StorageCache.SetSubNodes("/", nodes);
                return nodes;
            }
        }

        public Tree(XDocument treeDoc)
        {
            this._contentTreeProvider = new XMLContentTreeProvider(treeDoc);
        }

        // /Content/ComputerShop/About
        public Node GetNode(string path)
        {
            path = path.Trim('/');
            string[] pathParts = path.Split('/');

            Node currentNode = null;
            if (pathParts.Count() > 0)
            {
                string firstPath = pathParts[0];
                currentNode = this.Nodes.Where(p => p.Name.Equals(firstPath, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault();
            }

            foreach (string pathPart in pathParts.Skip(1))
            {
                Node node = currentNode.GetChild(pathPart);
                //node.Parent = currentNode;
                currentNode = node;

                if (currentNode != null)
                {
                    Context.Application.StorageCache.SetNode(currentNode);
                }
            }
            return currentNode;
        }

        public Node GetNode(Node parentNode, string relativePath)
        {
            string fullPath = parentNode.Path.CombineUrl(relativePath);
            return this.GetNode(fullPath);
        }

        public Node CreateNode(string parentNodePath)
        {
            return null;
        }
    
    }
}